// -------------------------------------------------
// BlinKit - BlinKit Library
// -------------------------------------------------
//   File Name: qjs_recursion_scope.cpp
// Description: RecursionScope Class
//      Author: Ziming Li
//     Created: 2022-04-24
// -------------------------------------------------
// Copyright (C) 2022 MingYang Software Technology.
// -------------------------------------------------

#include "./qjs_recursion_scope.h"

#include "blinkit/blink/renderer/core/dom/microtask.h"
#include "blinkit/blink/renderer/wtf/MainThread.h"

namespace BlinKit {
namespace qjs {

static std::unordered_map<JSContext *, unsigned> g_contexts;

RecursionScope::RecursionScope(JSContext *ctx) : m_ctx(ctx)
{
    ASSERT(isMainThread());

    auto it = g_contexts.find(m_ctx);
    if (g_contexts.end() != it)
        ++(it->second);
    else
        g_contexts.emplace(ctx, 1);
}

RecursionScope::~RecursionScope(void)
{
    auto it = g_contexts.find(m_ctx);
    ASSERT(g_contexts.end() != it);

    --(it->second);
    if (it->second > 0)
        return;

    g_contexts.erase(it);
    Microtask::PerformCheckpoint(JS_GetRuntime(m_ctx));
}

} // namespace qjs
} // namespace BlinKit
